import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useLoadingStore = defineStore('loading', () => {
  const loadingCount = ref(0)
  const loading = ref(false)

  function startLoading() {
    loadingCount.value++
    loading.value = true
  }

  function endLoading() {
    loadingCount.value = Math.max(0, loadingCount.value - 1)
    loading.value = loadingCount.value > 0
  }

  function withLoading<T>(promise: Promise<T>): Promise<T> {
    startLoading()
    return promise.finally(() => {
      endLoading()
    })
  }

  return {
    loading,
    startLoading,
    endLoading,
    withLoading
  }
}) 